#pragma once

#include "simulation/simulation_engine.h"
#include "kernel/interfaces/ILogger.h"
#include "kernel/interfaces/IConfiguration.h"
#include <QObject>
#include <memory>
#include <QHash>
#include <QString>

namespace application {

class MapApplicationService;

namespace vehicle {
    class VehicleService;
}

namespace simulation {

/**
 * @brief 仿真服务 - 管理仿真引擎生命周期
 * @details 作为 application 层的服务，负责初始化和管理仿真引擎
 */
class SimulationService : public QObject {
    Q_OBJECT

public:
    explicit SimulationService(
        std::shared_ptr<MapApplicationService> mapService,
        std::shared_ptr<kernel::ILogger> logger,
        QObject* parent = nullptr
    );
    ~SimulationService() = default;

    /**
     * @brief 初始化仿真服务
     */
    bool initialize();

    /**
     * @brief 获取仿真引擎
     */
    SimulationEngine* engine() { return m_engine.get(); }

    /**
     * @brief 检查是否启用仿真
     */
    bool isEnabled() const { return m_enabled; }

    /**
     * @brief 设置是否启用
     */
    void setEnabled(bool enabled) { m_enabled = enabled; }

    /**
     * @brief 播放仿真
     */
    void play();

    /**
     * @brief 暂停仿真
     */
    void pause();

    /**
     * @brief 恢复仿真（从暂停状态）
     */
    void resume();

    /**
     * @brief 停止仿真
     */
    void stop();

    /**
     * @brief 单步推进
     */
    void step(double deltaTime);

    /**
     * @brief 设置时间缩放
     */
    void setTimeScale(double scale);

    /**
     * @brief 获取仿真时间
     */
    double getSimulationTime() const;

    /**
     * @brief 记录仿真车辆的初始状态（由初始化过程调用）
     */
    void recordInitialVehicleState(int agvNumber, const QString& station, const QString& map);

    /**
     * @brief 将所有仿真车辆重置到配置中的初始位置
     */
    void resetVehiclesToInitialState();

signals:
    void simulationStateChanged(bool isPlaying, bool isPaused);

private:
    std::shared_ptr<kernel::ILogger> m_logger;
    std::unique_ptr<SimulationEngine> m_engine;
    bool m_enabled;

    struct SimulationVehicleState {
        QString station;
        QString map;
    };
    QHash<int, SimulationVehicleState> m_initialVehicleStates;
};

} // namespace simulation
} // namespace application
